package br.com.Formula;

import br.com.ConexaoBanco.ConexaoMySQL;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/*
 * CadastrarUsuario.java
 *
 * Created on 24/05/2011, 08:27:54
 */
/**
 *
 * @author Jayme Augusto Vara
 */
public class ExportarARFF extends javax.swing.JInternalFrame {

    /**
     * Creates new form CadastrarUsuario
     */
    public ExportarARFF() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        btnExportar = new javax.swing.JButton();

        jFileChooser1.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        jFileChooser1.setDialogTitle("");

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Exportar Arquivo ARFF");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/icone/16 x 16/apply.png"))); // NOI18N

        btnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icone/compfile.png"))); // NOI18N
        btnExportar.setText("Exportar");
        btnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportarActionPerformed(evt);
            }
        });
        btnExportar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnExportarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnExportar, javax.swing.GroupLayout.DEFAULT_SIZE, 527, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnExportar)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private String criaAtributos(String nomeAtributo, String nomeTabela, String nomeCampo) {
        String atrib = "@attribute " + nomeAtributo + " {";
        ResultSet rs;
        try {
            Connection com = ConexaoMySQL.getConexaoMySQL();
            Statement stm = com.createStatement();
            rs = stm.executeQuery("SELECT DISTINCT " + nomeCampo + " FROM " + nomeTabela + " ORDER BY " + nomeCampo + " ASC");
            rs.first();
            while (!rs.isAfterLast()) {
                atrib = atrib + rs.getString(nomeCampo).replace(" ", "_") + ", ";
                rs.next();
            }
            //Apaga o ulitmo espaço e a ulitma virgula adicionados no while
            atrib = atrib.substring(0, atrib.length() - 2);
            atrib = atrib + "}";
        } catch (SQLException ex) {
            Logger.getLogger(CadastrarPiloto.class.getName()).log(Level.SEVERE, null, ex);
        }
        return atrib;

    }

    private void btnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExportarActionPerformed
        //recebe se o usuario clicou no botao salvar ou cancelar
        jFileChooser1.setSelectedFile(new File("formula1.arff"));
        int salvar = jFileChooser1.showSaveDialog(this);
        File arq;
        //testa se ele escoulheu salvar
        if (salvar == JFileChooser.APPROVE_OPTION) {
            arq = jFileChooser1.getSelectedFile();
            String atributo, dados;

            try {
                //tenta criar o arquivo
                arq.createNewFile();
                FileWriter fileWriter = new FileWriter(arq, false);

                PrintWriter printWriter = new PrintWriter(fileWriter);

                printWriter.println("@RELATION formula1");
                printWriter.println("");

                //Pesquisar o atributo piloto
                atributo = criaAtributos("piloto", "piloto", "nom_piloto");
                printWriter.println(atributo);

                //Pesquisar o atributo parada
                atributo = criaAtributos("parada", "tipoparada", "nom_tipo");
                printWriter.println(atributo);

                //Pesquisar o atributo pneu
                atributo = criaAtributos("pneu", "pneu", "tipo_pneu");
                printWriter.println(atributo);

                //Pesquisar o atributo pneu
                atributo = criaAtributos("voltas", "cadparada", "num_volta");
                printWriter.println(atributo);

                //Pesquisar o atributo pneu
                atributo = criaAtributos("combustivel", "cadparada", "qtd_comb");
                printWriter.println(atributo);

                printWriter.println("");
                printWriter.println("@data");

                //pesquisar os dados

                dados = "";
                ResultSet rs;
                try {
                    Connection com = ConexaoMySQL.getConexaoMySQL();
                    Statement stm = com.createStatement();
                    rs = stm.executeQuery("SELECT p.nom_piloto, tp.nom_tipo, pn.tipo_pneu, cad.num_volta, cad.qtd_comb FROM cadparada as cad inner join piloto as p on cad.id_piloto = p.id_piloto inner join tipoparada as tp on cad.parada = tp.id_tipo inner join pneu as pn on cad.id_pneu = pn.id_pneu");
                    rs.first();
                    while (!rs.isAfterLast()) {
                        dados = rs.getString("nom_piloto").replace(" ", "_") + "," 
                              + rs.getString("nom_tipo").replace(" ", "_") + "," 
                              + rs.getString("tipo_pneu").replace(" ", "_") + "," 
                              + rs.getString("num_volta").replace(" ", "_") + "," 
                              + rs.getString("qtd_comb").replace(" ", "_");
                        printWriter.println(dados);
                        rs.next();
                    }

                } catch (SQLException ex) {
                    Logger.getLogger(CadastrarPiloto.class.getName()).log(Level.SEVERE, null, ex);
                }

                //libera a escrita
                printWriter.flush();
                //Fecha o arquivo
                printWriter.close();
                JOptionPane.showMessageDialog(null, "Arquivo exportado com sucesso!",
                        "Arquivo exportado com sucesso!", 1);

            } catch (IOException ex) {
                Logger.getLogger(ExportarARFF.class.getName()).log(Level.SEVERE, null, ex);
            }



        }
}//GEN-LAST:event_btnExportarActionPerformed
    private void btnExportarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnExportarKeyPressed
    }//GEN-LAST:event_btnExportarKeyPressed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExportar;
    private javax.swing.JFileChooser jFileChooser1;
    // End of variables declaration//GEN-END:variables
}
